﻿using System;
using System.Linq;
using ProjetoComperio.DataLayer.Entities;
using ProjetoComperio.DataLayer.Infra;

namespace ProjetoComperio.BusinessLogicLayer
{
    public class SubjectBLL : ComperioDataObject, ISubjectBLL
    {
        /// <summary>
        /// This method creates a new subject in db
        /// </summary>
        /// <param name="subject"></param>
        public void Create(Subject subject)
        {
            DbContext.Subjects.Add(subject);
            DbContext.SaveChanges();
        }

        /// <summary>
        /// This method retrieves the subjects related to a specific contribuition
        /// </summary>
        /// <param name="contributionID"></param>
        /// <returns></returns>
        public IQueryable<Subject> RetrieveSubjects(Int32 contributionID)
        {
            return DbContext.Subjects.Where(subject => subject.ContributionID == contributionID);
        }

        /// <summary>
        /// This method retrieves all the subjects from data base
        /// </summary>
        /// <param name="contributionID"></param>
        /// <returns></returns>
        public IQueryable<Subject> RetrieveSubjects()
        {
            return DbContext.Subjects;
        }


        /// <summary>
        /// This method retrieves a specific subject 
        /// </summary>
        /// <param name="subjectID"></param>
        /// <returns></returns>
        public Subject RetrieveSubject(Int32 subjectID)
        {
            return DbContext.Subjects.Where(subject => subject.SubjectID == subjectID).FirstOrDefault();
        }

        /// <summary>
        /// This method removes a specific subject from db
        /// </summary>
        /// <param name="subjectID"></param>
        public void Remove(Int32 subjectID)
        {
            foreach (var comment in DbContext.Comments.Where(c => c.SubjectId == subjectID))
                DbContext.Comments.Remove(comment);

            DbContext.Subjects.Remove(RetrieveSubject(subjectID));
            DbContext.SaveChanges();
        }
    }
}
